package com.felix.thread;

import org.checkerframework.checker.units.qual.K;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * SemaphoreDemo
 *
 * @author xuejinhua
 * @date 2018/10/12 10:29
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        for (int i = 0; i < 4; i++) {
            new Thread(new SemaphoreTest()).start();
        }
    }

    static class SemaphoreTest implements Runnable {

        public static Semaphore semaphore = new Semaphore(2, true);

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread() + " getting semaphore");
                Thread.sleep(1000);
                System.out.println(Thread.currentThread() + " releasing semaphore");
                semaphore.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
